package com.example.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author zhangguangyan
 * @Date 2023/09/17/ 10:31:32
 */
@Service
public class AsynaService {
    @Autowired
    private AsyncService asyncService;

    public List<Integer> getList() throws ExecutionException, InterruptedException {
        List<CompletableFuture<List<Integer>>> futures = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            futures.add(asyncService.list(new ArrayList<>()));
        }

        CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
        allOf.join(); // 等待所有异步任务完成

        // 收集所有异步任务的结果
        List<Integer> result = futures.stream()
                .map(future -> {
                    try {
                        return future.get();
                    } catch (Exception e) {
                        // 处理异常
                        return new ArrayList<Integer>();
                    }
                })
                .flatMap(List::stream)
                .collect(Collectors.toList());

        return result;
    }
}
